package cbs.demo.graal;

import cbs.demo.mapper.PatientMapper;
import com.oracle.svm.core.annotate.AutomaticFeature;
import com.oracle.svm.core.jdk.proxy.DynamicProxyRegistry;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.hosted.RuntimeReflection;

import java.lang.reflect.Proxy;

/**
 * 这个类中的代码是在NativeImage编译的时候运行的
 */
@AutomaticFeature
public class NativeImageGen implements Feature {
    //这里我们直接写死了这个类名,实际项目中可以根据配置文件中配置的包名,扫描包下所有类进行注册
    private static String className = "cbs.demo.domain.Patient";
    private static String MapperName = "cbs.demo.mapper.PatientMapper";

    @Override
    public void beforeAnalysis(BeforeAnalysisAccess access) {
        try {
            var loader = Thread.currentThread().getContextClassLoader();
            var clazz = loader.loadClass(className);
            //注册该类
            RuntimeReflection.register(clazz);
            RuntimeReflection.register(clazz.getDeclaredConstructor());

            var proxy = Proxy.class;
            RuntimeReflection.register(proxy);
            RuntimeReflection.register(proxy.getConstructors());
            RuntimeReflection.register(proxy.getDeclaredConstructors());

//            RuntimeReflection.register(clazz.getFields());
//            RuntimeReflection.register(clazz.getMethods());


            var proxyRegistry = ImageSingletons.lookup(DynamicProxyRegistry.class);
            //这里直接写死,实际可以从包中扫描
//            var mapperClass = loader.loadClass(MapperName);
            proxyRegistry.addProxyClass(PatientMapper.class);
            RuntimeReflection.register(PatientMapper.class);
//            RuntimeReflection.register(mapperClass.getMethods());
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
